<?php

namespace App\Service\CommodityService;

use App\Service\AppService\SystemCacheConfigService;
use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Model\CommodityModel\SupplierCompany;
use Hyperf\DbConnection\Db;
use App\Model\CommodityModel\SupplierCommodity;

/**
 * 韩免供应商拉取商品
 * @author chenshubo
 */
class SupplierCommodityHanMianPullLogService extends BaseService
{
    const PULL_FLAG = 'shophanmian';
    const TIME_WAIT = 240; //分钟
    const PULL_USER_COUNT = 10; //每次同时拉取供应商的数量

    /**
     * 开启计划任务
     */
    public function runTask($pullFlag = '')
    {
        $config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('channel_task_user_limit');
        if (empty($config)) {
            return Normal::returnCode(Normal::FAIL, '参数未配置');
        }
        //所有供应商拉取完成间隔时间
        $SupplierPullWaitTime = self::TIME_WAIT;
        //预计下次拉取商品时间
        $CommodityGetNetPeriod = date("Y-m-d H:i:s", time() + $SupplierPullWaitTime * 60);

        $supplierCode = $pullFlag ?: self::PULL_FLAG;
        $res = SupplierCommodityPullLogService::instance()->getWaitPullSupplierWareHouseInfosByThirdPartyPlatformCode($supplierCode);
        if ($res['code'] != Normal::SUC) {
            return $res;
        }
        
        $suppliers = $res['data'];

        //获取供应商参数
        $SupplierIDs  = array_column($suppliers, 'SupplierID');
        //初始化拉取状态
        $updateArr = [
            'CommodityGetTaskStatus'    => 0,
            'CommodityGetFinishCount'   => 0,
            'CommodityGetFinishUseTime' => 0.000,
        ];
        SupplierCompany::instance()->whereIn('ID', $SupplierIDs)->update($updateArr);
        
        foreach ($suppliers as $supplier) 
        {
            //获取供应商参数
            $company_code   = $supplier['ThirdPartyPlatformCode'] ? $supplier['ThirdPartyPlatformCode'] : $supplier['SupplierCode'];
            $SupplierID     = $supplier['SupplierID'];
            $CommodityGetStartTime = microtime(true);

            //获取行云的所有分类
            $apiBody = $supplier['JsonBody'];
            $routerClass = '\\App\\Service\\OrderService\\OrderRouteService\\' . ucfirst($company_code);
            
            $page = 1;
            $currentLastPage = $currentPage  = $CommodityGetTotal = 0;
            
            
            if(!isset($apiBody["url"])){
                return Normal::returnCode(Normal::FAIL, "商品url不能为空");
            }
            
            logger('info','hanmian-goods-pull')->info("开始拉取商品");
            
            $url        = $apiBody["url"];
            $fileName   = $supplierCode."goods".date("YmdHis",time()).".log";
            $pageSize   = $param["limit"]??100;
            $response   = file_get_contents($url);
            file_put_contents($fileName, $response);
            
            
            //开始处理商品数据
            $goodSteamLogArray = file($fileName);
            $batchFiles = array_chunk($goodSteamLogArray,$pageSize);
            foreach ($batchFiles as $page => $evalFiles)
            {
                if($page == 100 ) 
                {
                    break;
                }
                
                logger('info','hanmian-goods-pull')->info("当前商品数量:{$pageSize}");
                $evalGoodsItems = [];
                foreach ($evalFiles as $file)
                {
                    $string = str_replace("<<<","\r\n", $file);
                    $goods = \explode("\r\n", $string);
                    unset($goods[0]);
            
                    $temp = [];
                    foreach($goods as $value)
                    {
                        $tp = \explode(">>>", $value);
                        $temp[$tp[0]] = $tp[1];
                    }
                    foreach ($temp as $k =>$v){
                        if (strpos($v, "\t") !== false) {
                            $temp[$k] = str_replace("\t","", $v);
                        }
                        if (strpos($v, "\n") !== false) {
                            $temp[$k] = str_replace("\n","", $v);
                        }
                    }
                    
                    $str = json_encode($temp,JSON_UNESCAPED_UNICODE);
                    logger('info','hanmian-goods-pull')->info("当前商品信息:{$str}");
                    $evalGoodsItems[]= $this->queryPageGoodsList($SupplierID,$temp);
                }
                //开始同步到MQ队列$evalGoodsItems
                if (empty($evalGoodsItems)) {
                    $currentLastPage = $currentPage;
                    break;
                }
                $pull_count = count($evalGoodsItems);
                $CommodityGetTotal += $pull_count;
                $updateArr = [
                    'CommodityGetTaskStatus'    => 1,
                    'CommodityGetFinishCount'   => Db::raw("CommodityGetFinishCount+{$pull_count}")
                    ];

                SupplierCompany::instance()->where('ID', $SupplierID)->update($updateArr);
                $MessageBody  = [
                    'SupplierID'        => $SupplierID,
                    'SupplierCode'      => $company_code,
                    'IsFirstPage'       => $page == 1 ? 1 : 0,
                    'DataPage'          => $page,
                    'IsLastPage'        => 0,
                    'GoodsItemList'     => $evalGoodsItems
                ];
                SupplierCommodityPullLogService::instance()->publish($MessageBody);
            }
            
            logger('info','hanmian-goods-pull')->info("当前完成更新商品总数:10000条");
            //更新总数量
            $MessageBody  = [
                'SupplierID'        => $SupplierID,
                'SupplierCode'      => $company_code,
                'IsFirstPage'       => 0,
                'DataPage'          => 1,
                'IsLastPage'        => 1,
                'GoodsItemList'     => []
            ];
            SupplierCommodityPullLogService::instance()->publish($MessageBody);
            
            //拉取完成
            $updateArr = [
                'CommodityGetTaskStatus'    => 2,
                'CommodityGetContents'      => '拉取完成',
                'CommodityGetFinishUseTime' => bcsub(microtime(true), $CommodityGetStartTime, 3),
                'CommodityGetNetPeriod'     => $CommodityGetNetPeriod
            ];
            SupplierCompany::instance()->where('ID', $SupplierID)->update($updateArr);
            
            @unlink($filename);
            
        }
        return Normal::returnCode(Normal::SUC, '拉取完成');
    }

    /**
     * 处理商品分页报文
     * @param array $imageList
     * @param array $articleList
     * @param string $className
     */
    public function queryPageGoodsList($hmCompanyId,array $goodsData)
    {
        $queryGoodsList = [];
        $goodsImgList = [];//详情图
        $goodsKey     = (string)$goodsData["sku"];//供应商skucode
        $goodsBarCode = (string)$goodsData["srccd"];//国际条形码
        $goodsName    = $goodsData["pname"];//商品名
        $goodsNameAlias= $goodsData["ref"];//商品别名
        $goodsBrand   = $goodsData["bname"];//品牌
        $className    = '';//分类名
        $goodsPrice   = $goodsData["price"];//价格
        $stockNumber  = $goodsData["stock"];//库存
        $goodsDes     = $goodsData["pname"];//描述
        $taxRate      = "0.091";//税率
        $goodsSpec    = [];//规格
        $goodsOriginPlace    = '';//产地
        $SupplierCommodityType    = 2;//类型一般贸易
        $goodsLink    = '';//商品链接
        
        //开始组装数据
        $SupplierCommodityInfo = [];

        //通过原始供应商sku生成新的供应商sku
        $goodsSkuCode = HmCommodityGoodsService::instance()->makeMd5SkuCode($hmCompanyId,$goodsKey);
        //判断商品是否已经翻译过
        $SupplierCommodityModel = SupplierCommodity::instance()->where("SupplierCommoditySkuCode",$goodsSkuCode)->first();
        if($SupplierCommodityModel){
            $SupplierCommodityInfo = $SupplierCommodityModel->toarray();
        }
        if(empty($SupplierCommodityInfo) or $SupplierCommodityInfo["IsTranslate"] == 0){
            //组合商品组
            $queryGoodsList = [
                'goodsImgList'      => $goodsImgList,
                'goodsName'         => $goodsName,
                'goodsNameAlias'    => $goodsNameAlias,
                'goodsBrand'        => HmCommodityGoodsService::instance()->transferByHanGuoLanguageToChinese($goodsBrand),
                'goodsBrandAlias'   => $goodsBrand,
                'goodsClass'        => $className,
                'goodsClassAlias'   => $className,
                'goodsPrice'        => $goodsPrice,
                'goodsSkuCode'      => $goodsSkuCode,
                'goodsBarCode'      => $goodsBarCode,
                'stockNumber'       => $stockNumber,
                'goodsDes'          => $goodsDes,
                'taxRate'           => $taxRate,
                'goodsOriginPlace'  => '',
                'goodsSpec'         => [],
                'commodityType'     => $SupplierCommodityType,
                'goodsLink'         => $goodsLink,
                'goodsKey'          => $goodsKey,
                ];
        }else{
            //组合商品组
            $queryGoodsList = [
                'goodsImgList'      => $goodsImgList,
                'goodsName'         => $SupplierCommodityInfo["SupplierCommodityName"],
                'goodsNameAlias'    => $goodsName,
                'goodsBrand'        => $SupplierCommodityInfo["SupplierCommodityBrand"],
                'goodsBrandAlias'   => $goodsBrand,
                'goodsClass'        => $SupplierCommodityInfo["SupplierCommodityClassify"],
                'goodsClassAlias'   => $className,
                'goodsPrice'        => $goodsPrice,
                'goodsSkuCode'      => $goodsSkuCode,
                'goodsBarCode'      => $goodsBarCode,
                'stockNumber'       => $stockNumber,
                'goodsDes'          => $goodsDes,
                'taxRate'           => $taxRate,
                'goodsOriginPlace'  => $SupplierCommodityInfo["SupplierCommodityOriginPlace"],
                'goodsSpec'         => [],
                'commodityType'     => $SupplierCommodityType,
                'goodsLink'         => $goodsLink,
                'goodsKey'          => $goodsKey,
            ];
        }
        return $queryGoodsList;
    }
}
